<template>
  <div class="integralPage">
    <el-form
      ref="formRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="integralPage-ruleForm"
    >
      <el-form-item label="认证时间" prop="time">
        {{ ruleForm.nowTime }}
      </el-form-item>
      <el-form-item v-if="Number(privacyTime) === 0" label="管理员电话">
        <el-input
          :model-value="hidden(ruleForm.newPhone, 3, 4)"
          disabled
          placeholder="请输入管理员电话"
        />
      </el-form-item>
      <el-form-item v-else label="管理员电话" prop="newPhone">
        <el-input
          v-model="ruleForm.newPhone"
          disabled
          placeholder="请输入管理员电话"
        />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input
          v-model="ruleForm.code"
          maxlength="6"
          placeholder="请输入验证码"
        >
          <template #append>
            <el-button
              type="primary"
              :loading="loading.code"
              @click="getCode"
            >
              <span v-if="!loading.code">获取验证码</span>
              <span v-else>{{ codeCountTime }} s</span>
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading.submit" @click="submit(formRef)">
          确定
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { defineComponent, nextTick, onBeforeMount, reactive, ref, shallowRef } from 'vue';

import {
  getAdminPhone,
  getPrivacyCode,
  verifyPrivacyCode
} from '@/api/privacy'
import { encrypt } from '@/utils/rsaEncrypt.js'

defineComponent({
  name: 'PrivacyPage'
})

const formRef = ref();
let ruleForm = reactive({
  nowTime: '',
  newPhone: '',
  code: '',
})

function rulePhone (rule, value, callback) {
  if (!value) {
    return callback(new Error('请输入新手机号'))
  } else if (!/^1[3456789]\d{9}$/.test(value)) {
    return callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}
function ruleCode (rule, value, callback) {
  if (!value) {
    return callback(new Error('请输入验证码'))
  } else {
    callback()
  }
}
const rules = {
  newPhone: [{ required: true, validator: rulePhone, trigger: 'blur' }],
  code: [{ required: true, validator: ruleCode, trigger: 'blur' }],
}

let loading = reactive({
  submit: false,
  code: false,
})
let timer = reactive({
  code: null
})
const TIME_COUNT = 120; // 更改倒计时时间
let codeCountTime = shallowRef(false);

// 获取管理员电话
function getPhone () {
  getAdminPhone().then((res) => {
    ruleForm.newPhone = res.data
  })
}
// 获取验证码
function getCode () {
  if (!ruleForm.newPhone) {
    ElMessage.error('请填写手机号')
    return
  }
  if (!/^1[3456789]\d{9}$/.test(ruleForm.newPhone)) {
    ElMessage.error('请填写正确手机号')
    return
  }
  if (!timer.code) {
    loading.code = true
    codeCountTime.value = TIME_COUNT
    getPrivacyCode({
      phone: ruleForm.newPhone
    }).then(res => {
      if (res.code === '') {
        ElMessage.success('发送成功，请注意查看手机短信')
      }
      timer.code = setInterval(() => {
        if (codeCountTime.value > 0 && codeCountTime.value <= TIME_COUNT) {
          codeCountTime.value--
        } else {
          clearInterval(timer.code) // 清除定时器
          loading.code = false
        }
      }, 1000)
    })
  }
}
// 确定
function submit (formEl) {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      loading.submit = true;
      timer.code = null
      loading.code = false
      verifyPrivacyCode({
        code: encrypt(ruleForm.code),
        username: encrypt(ruleForm.newPhone),
      }).then(res => {
        if (res.data) {
          ElMessage.success('二次认证成功，该认证24小时内有效，超过时间需要重新认证')
          formRef.value.resetFields()
          location.reload()
        }
      }).finally(() => {
        loading.submit = false;
      })
    } else {
      return false
    }
  })
}
// 中间部分
function hidden (str, frontLen, endLen) {
  if (!str) { return '' }
  let endLenData = 0
  if (str.length !== 2) {
    endLenData = endLen
  }
  const len = str.length - frontLen - endLenData
  let xing = ''
  for (let i = 0; i < len; i++) {
    xing += '*'
  }
  return (
    str.substring(0, frontLen) +
        xing +
        str.substring(str.length - endLenData)
  )
}

const privacyTime = localStorage.getItem('privacyTime');
onBeforeMount(() => {
  getPhone()
  // 获取认证的时间
  if (Number(privacyTime) === 0) {
    ruleForm.nowTime = '未认证'
  } else {
    var time = new Date(Number(privacyTime))
    var year = time.getFullYear()
    var month = time.getMonth() + 1
    var day = time.getDate()
    var hours = time.getHours()
    var minutes = time.getMinutes()
    ruleForm.nowTime =
        year + '-' + month + '-' + day + ' ' + hours + ':' + minutes
  }
})
</script>

<style lang="scss" scpoed>
.integralPage {
  padding: 32px 20px;
  .integralPage-ruleForm{
    max-width: 600px;
  }
  .el-form-item__label {
    font-weight: bold;
  }
  .el-input {
    width: 70%;
    .el-input__inner {
      height: 38px;
    }
  }
  .el-button {
    height: 38px;
  }
}
</style>
